import React, { useEffect, useState, useRef, useContext } from 'react'
import picUrl from '@/assets/img/plateBackground.png'
import styles from './index.less'
import IconFont from "@/components/iconfont";
import { getLyric, getSongdetailByids, getComments, getSimiSong } from '@/api'
import { lyricType } from '@/interfaces/types'
import myContext from '@/store/my-context';
let isAutoScroll: boolean = false
let runLast: NodeJS.Timeout | null = null
const Lyricpage: React.FC<{isDisplay:boolean}> = ({isDisplay}) => {
    const { state } = useContext(myContext)
    const lyricEle = useRef<any>(null)
    const playLineEle = useRef<any>(null)
    const [songDetail, setSongDetail] = useState<any>(null)
    const [lyric, setLyric] = useState<Array<lyricType>>([])
    const [comments, setComments] = useState<any>(null)
    const [simiSongs, setSimiSongs] = useState<any>(null)
    const [isLike, setIsLike] = useState<boolean>(false)
    const [playLyNum, setPlayLyNum] = useState<number>(0)
    const clearAll = () => {
        setIsLike(false)
        setComments(null)
        setLyric([])
    }
    const addBracketsToText = (text: string): string => {
        if(/^\(.*\)$/.test(text)){
            return text
        }
        return `(${text})`
    }
    useEffect(() => {
        clearAll()
        try {
            let songId = state.playInfo.playingId
            if (songId > 0) {
                getLyric({ id: songId }).then((res) => {
                    // console.log(res);
                    try {
                        let tlyricObj: { [key: string]: string } = {}
                        if (res?.tlyric?.lyric) {
                            res.tlyric.lyric.split(/\n+/).filter((lyricLine: string) => {
                                let arrt: Array<string> = lyricLine.split(/\[|\]/)
                                let time: Array<number> = []
                                let text: string = ''
                                arrt.forEach((lyricde: string) => {
                                    if (/\d{1,3}[:]\d{1,3}/.test(lyricde)) {
                                        let timeString: Array<string> = lyricde.split(':')
                                        time.push(Number(timeString[0]) * 60 + Number(timeString[1]))
                                    } else if (lyricde.length > 0) {
                                        text = lyricde
                                    }
                                })
                                if (time.length > 0 && text.length > 0) {
                                    time.forEach((timeS: number) => {
                                        if (timeS > 0) {
                                            tlyricObj[`${timeS.toFixed(3)}`] = text
                                        }
                                    })
                                }
                            })
                            // console.log(tlyricObj)
                        }
                        if (res?.lrc?.lyric) {
                            let arr: Array<lyricType> = []
                            const nullLyric: string = '\. \. \. \. \. \. '
                            console.log(res.lrc.lyric)
                            //截取  XX [ XX \n XX
                            res.lrc.lyric.split(/\n+/).filter((lyricLine: string) => {
                                
                                let arrt: Array<string> = lyricLine.split(/\[|\]/)
                                let time: Array<number> = []
                                let text: string = nullLyric
                                arrt.forEach((lyricde: string) => {
                                    if (/\d{1,3}[:]\d{1,3}/.test(lyricde)) {
                                        let timeString: Array<string> = lyricde.split(':')
                                        time.push(Number(timeString[0]) * 60 + Number(timeString[1]))
                                    } else if (lyricde.length > 0) {
                                        text = lyricde
                                    }
                                })
                                time.forEach((resIn: number) => {
                                    arr.push({
                                        timeS: resIn,
                                        text: text,
                                        ttext: tlyricObj[`${resIn.toFixed(3)}`]
                                            || null
                                    })
                                })
                            })
                            if (arr?.length > 0) {
                                arr.sort(sortByTime)
                                setLyric(arr)
                            } else {
                                throw new Error('歌词获取错误')
                            }
                        }
                    } catch (err) {
                        console.log(err)
                    }
                    if (res?.nolyric) {

                    }
                })
                getSongdetailByids({ ids: songId }).then((res) => {
                    if (res?.songs?.length > 0) {
                        setSongDetail(res?.songs[0])
                    }
                })
                getComments({ id: songId, limit: 20 }).then((res) => {
                    setComments(res || null)
                })
                getSimiSong({ id: songId, limit: 5 }).then(res => {
                    if (res?.songs?.length > 0) {
                        setSimiSongs(res.songs)
                    }
                })
            }
        } catch (err) {
            console.log(err)
        }
        return clearAll
    }, [state.playInfo.playingId])
    const setNum = (ttime: number) => {
        for (let i: number = 0; i < lyric.length; i++) {
            if (i === lyric.length - 1//必须加上最后一句的判断
                || (i === 0
                    && ttime < lyric[i].timeS)
                || (ttime >= lyric[i].timeS
                    && ttime < lyric[i + 1].timeS)

            ) {
                setPlayLyNum(i)
                break
            }
        }
    }
    const sortByTime = (a: lyricType, b: lyricType) => {
        return a.timeS - b.timeS
    }
    const autoScroll = (tonScroll: boolean = true): void => {
        if (tonScroll && lyricEle.current?.scrollTop >= 0) {
            let scrTop = playLineEle?.current?.offsetTop
                - lyricEle?.current?.offsetTop
                - lyricEle?.current?.offsetHeight / 2
                + playLineEle?.current?.offsetHeight / 2 //将播放行置于中间
                || 0
            //chrome不需自己判断scrollTop是否越界，其他浏览器未知
            if(scrTop < 0){
                scrTop = 0
            }
            // console.log(scrTop)
            lyricEle.current.scrollTop = scrTop
            // console.log()
        }
    }
    useEffect(() => {
        let time = state.playInfo.currentTime
        if (time > 0) {
            setNum(time)
        }
    }, [state.playInfo.currentTime])
    useEffect(() => {
        if (playLyNum && playLyNum > 0) {
            if (!runLast) {
                isAutoScroll = true
                autoScroll()
            }
        }
    }, [playLyNum])
    return (
        <div 
        className={styles['page']} 
        style={isDisplay
        ?{transform:'scale(1)'}
        :{
            visibility:'hidden',
            transform:'scale(0.1)'
        }}>
            <div className={styles['page-top']}
            style={isDisplay?{}:{display:'none'}}>
                <div className={styles['page-top-left']}>
                    <div style={
                        state.playInfo.isPlay ? {} : { animationPlayState: 'paused' }
                    } className={styles['plate']}>
                        <img
                            className={styles['plate-img']}
                            src={picUrl}
                        />
                        <img
                            src={songDetail?.al?.picUrl || ''}
                            className={styles['plate-cover']}
                        />
                    </div>
                    <div
                        className={styles['plate-bottom']}
                    >
                        <a >
                            <IconFont onClick={() => {
                                setIsLike(!isLike)
                            }}
                                style={isLike
                                    ? {
                                        color: 'rgb(236,65,65)'
                                    }
                                    : {
                                    }}
                                type={isLike
                                    ? "iconaixin"
                                    : 'iconaixin1'
                                }
                            />
                        </a>
                        <a >
                            <IconFont type='iconxiazai1' />
                        </a>
                        <a >
                            <IconFont type='iconshoucangjia1' />
                        </a>
                        <a >
                            <IconFont type='iconfenxiang1' />
                        </a>
                    </div>
                </div>
                <div className={styles['page-top-right']}>
                    <div className={styles['song-detail']}
                    >
                        <span className={styles['song-title']}>
                            {songDetail?.name}
                        </span>
                        <br />
                        <span className={styles['song-detailbox']}>
                            <span className={styles['song-info-type']}>
                                专辑:
                            </span>
                            <a
                                className={styles['song-info-text']}
                            >
                                {songDetail?.al?.name}
                            </a>
                        </span>
                        <span className={styles['song-detailbox']}>
                            <span className={styles['song-info-type']}>
                                歌手:
                            </span>
                            <a className={styles['song-info-text']}>
                                {songDetail?.ar[0]?.name}
                            </a>
                        </span>
                        <span className={styles['song-detailbox']}>
                            <span className={styles['song-info-type']}>
                                来源:
                            </span>
                            <a className={styles['song-info-text']}>
                                state...text
                            </a>
                        </span>

                    </div>
                    <div ref={lyricEle} className={styles['song-lyric']}
                        onScroll={() => {
                            if(isAutoScroll){
                                isAutoScroll = false
                            }else if (runLast) {
                                clearTimeout(runLast)
                                runLast = setTimeout(() => {
                                    //滚动后 6s内无下一次滚动引发
                                    autoScroll()
                                    runLast = null
                                }, 6000)
                            }else{
                                runLast = setTimeout(() => {
                                    autoScroll()
                                    runLast = null
                                }, 6000)
                            }
                        }}
                    >
                        {
                            lyric.length > 0
                                ? (
                                    lyric.map((res: lyricType, index: number) => (
                                        index === playLyNum
                                            ? <p ref={playLineEle} style={{
                                                fontWeight: 'bold',
                                                fontSize: '16px',
                                                color: '#000'
                                            }}
                                            >
                                                {res.text}
                                                {res.ttext
                                                    && (
                                                        <p style={{
                                                            fontSize: '15px',
                                                            fontWeight: 'normal',
                                                            color: '#000'
                                                        }}
                                                        >
                                                            {addBracketsToText(res.ttext)}
                                                        </p>)
                                                }

                                            </p>
                                            : <p>
                                                {res.text}
                                                {res.ttext
                                                    && (
                                                        <p style={{ fontSize: '15px' }}>
                                                            {addBracketsToText(res.ttext)}
                                                        </p>)
                                                }
                                            </p>

                                    ))
                                )
                                : (<p style={{ fontSize: '18px' }}
                                >暂无歌词
                                </p>)
                        }
                    </div>
                </div>
            </div>
            <div className={styles['page-bottom']}
            style={isDisplay?{}:{display:'none'}}>
                <div className={styles['page-bottom-main']}>
                    <div className={styles['input-comment']}>
                        <h2>评论</h2>
                        <h4>(已有{comments?.total}条评论)</h4>
                        <textarea rows={3} cols={20} placeholder='发表评论'></textarea>
                    </div>
                    <div className={styles['hotcommends']}>

                    </div>
                </div>
                <div className={styles['page-bottom-side']}>
                    <p>包含这首歌的歌单</p>
                    <div className={styles['list']}>
                        <img src="" alt="" />
                        <div>
                            <span></span>
                            <br />
                            <span></span>
                        </div>
                    </div>
                    <p>相似歌曲</p>
                    {simiSongs &&
                        (simiSongs.map((res: any) => (
                            <a className={styles['list']}>
                                <img src={res?.album?.picUrl} alt="" />
                                <div>
                                    <span style={{ color: 'rgb(30,30,30)' }}>
                                        {res?.name}
                                    </span>
                                    <br />
                                    <span style={{ color: 'rgb(96,96,97)' }}>
                                        {res?.artists[0]?.name}
                                    </span>
                                </div>
                            </a>
                        ))
                        )
                    }
                </div>
            </div>

        </div>
    )
}
export default Lyricpage